<template>
  <div class="page order-details">
    <div class="scroll-view">
      <contract ref="contract" :params="contractParams"/>
      <customHeader middleTitle="订单详情" @leftCallBack="handleBack"/>
      <div class="page-body">
        <div class="order-state" v-if="resultObject.status==1">
          <i class="zhk-ddfk"></i>
          <div class="order-info">
            <p>待付款</p>
            <p>剩余时间：{{restTime}}</p>
          </div>
          <div class="order-btn" @click="cancelOrder">取消订单</div>
        </div>
        <div class="order-state" v-if="resultObject.status==2">
          <i class="zhk-ddfh"></i>
          <div class="order-info">
            <p class="vertical-center">待处理</p>
            <!-- <p>设备稍后发出，请耐心等待…</p> -->
          </div>
          <router-link v-if="orderType && !orderTypes.includes(orderType)" :to="{path:`/mallList/orderRecord/orderDetails/viewLogistics`,query:{orderId:resultObject.orderId}}">
            <div class="order-btn">查看物流</div>
          </router-link>
        </div>
        <div class="order-state" v-if="resultObject.status==3">
          <i class="zhk-jywc"></i>
          <div class="order-info">
            <p class="vertical-center">已完成</p>
            <!-- <p v-html="'更新时间：'+CommonUtil.timestampToTime(resultObject.payCompleteTime)"></p> -->
          </div>
          <router-link v-if="orderType && !orderTypes.includes(orderType)" :to="{path:`/mallList/orderRecord/orderDetails/viewLogistics`,query:{orderId:resultObject.orderId}}">
            <div class="order-btn">查看物流</div>
          </router-link>
        </div>
        <ul class="recive-info" v-if="!resultObject.linkManEmail&&resultObject.linkMan&&resultObject.linkMobile">
          <li>
            <i class="zhk-dw text-right"></i>
            <div class="context-left">
              <div>
                <span class="main-text text-left">{{resultObject.linkMan}}</span>
                <span class="main-text text-left">{{resultObject.linkMobile}}</span>
              </div>
              <p>{{resultObject.address}}</p>
            </div>
          </li>
        </ul>
        <ul class="recive-info" v-if="resultObject.linkManEmail">
          <li>
            <i class="zhk-dxtg text-right"></i>
            <div class="context-left">
              <div>
                <span class="main-text text-left">{{resultObject.linkMan}}</span>
                <span class="main-text text-left">{{resultObject.linkMobile}}</span>
              </div>
              <p>{{resultObject.linkManEmail}}</p>
            </div>
          </li>
        </ul>
        <ul class="form-style-top" v-for="(machineListsItem,index) in resultObject.machineLists" :key="index">
          <li class="order-time" v-if="machineListsItem.shopName && !contract">
            <i class="zhk-md" />
            <span>{{machineListsItem.shopName}}</span>
          </li>
          <li class="order-list" v-for="(item,index) in machineListsItem.lists" :key="index">
            <div class="context-left">
              <img class="mainImg" :src="devicePic(item.machineType)" alt="" />
            </div>
            <!-- 聚客宝产品不显示单价，数量为1 -->
            <div class="context-right" v-if="jkbTypes.includes(item.machineType)">
              <div>
                <span class="text-left">{{item.machineName}}</span>
                <span class="text-right">x1</span>
              </div>
            </div>
            <div class="context-right" v-else>
              <div>
                <span class="text-left">{{item.machineName}}</span>
                <span class="text-right">¥ {{item.price}}</span>
              </div>
              <div>
                <span class="text-left"></span>
                <span class="text-right">x{{item.buyNum}}</span>
              </div>
            </div>
          </li>
          <li>
          </li>
        </ul>
        <ul class="inventory-list">
          <li>
            <div class="context-left">
              <span>商品总价</span>
            </div>
            <div class="context-right">
              <span>{{resultObject.totalAmount}}元</span>
            </div>
          </li>
          <li>
            <div class="context-left">
              <span>优惠金额</span>
            </div>
            <div class="context-right">
              <span>{{discountAmount}}元</span>
            </div>
          </li>
          <li v-if="CommonUtil.needExpiryTimeMall(machineType)">
            <div class="context-left">
              <span>有效期</span>
            </div>
            <div class="context-right">
              <span>{{CommonUtil.needExpiryTimeMall(machineType)}}</span>
            </div>
          </li>
        </ul>
        <ul class="linebar-list linebar-list-top" v-if="resultObject.status">
          <li>
            <div class="context-left">
              <span v-html="resultObject.status==1?'应付金额':'实付金额'"></span>
            </div>
            <div class="context-right">
              <span v-html="resultObject.status==1? '¥'+ resultObject.totalAmount:'¥'+ resultObject.realAmount"></span>
            </div>
          </li>
        </ul>
        <!-- 聚客宝订购门店列表 -->
        <ul class="shop-ul" v-if="contract">
          <li>
            <i class="zhk-md" />
            <span>订购门店</span>
          </li>
          <li v-for="(item,index) in contract.shopList" :key="index">
            <p class="text-left">{{item.shopName}}</p>
            <p class="text-left">{{item.shopId}}</p>
          </li>
        </ul>
        <ul class=" form-style linebar-list-top ">
          <li>
            <span class="required ">备注</span>
            <div v-if="resultObject.remark ">{{resultObject.remark}}</div>
            <div class="none " v-else>无</div>
          </li>
          <li>
            <span class="required ">邀请码</span>
            <div v-if="resultObject.invitCode ">{{resultObject.invitCode}}</div>
            <div class="none " v-else>无</div>
          </li>
        </ul>

        <div v-if="resultObject.status==1 " class="orderbottom-info ">
          <p @click="doCopy(resultObject.orderId) ">订单编号：{{resultObject.orderId}}
            <!-- <span class="copy ">复制</span> -->
          </p>
          <p>已签署协议：
            <span class="agreement " @click="jumpToserviceContract ">《{{CommonUtil.isMessagePackage(machineType)?"短信推广服务在线协议":"同福商家产品服务协议"}}》</span>
          </p>
          <p v-if="contract">已签署合同：<span class="agreement" @click="showJkbContract">《聚客宝软件服务合同》</span></p>
          <p v-html=" '下单时间：'+CommonUtil.timestampToTime(resultObject.createTime) "></p>
        </div>
        <div v-if="resultObject.status==2 " class="orderbottom-info ">
          <p @click="doCopy(resultObject.orderId) ">订单编号：{{resultObject.orderId}}</p>
          <p>订购方式：购买</p>
          <p>已签署协议：
            <span class="agreement " @click="jumpToserviceContract ">《{{CommonUtil.isMessagePackage(machineType)?"短信推广服务在线协议":"同福商家产品服务协议"}}》</span>
          </p>
          <p v-if="contract">已签署合同：<span class="agreement" @click="showJkbContract">《聚客宝软件服务合同》</span></p>
          <p v-html=" '下单时间：'+CommonUtil.timestampToTime(resultObject.createTime) "></p>
          <p v-html=" '付款时间：'+CommonUtil.timestampToTime(resultObject.updateTime) "></p>
        </div>
        <div v-if="resultObject.status==3 " class="orderbottom-info ">
          <p @click="doCopy(resultObject.orderId) ">订单编号：{{resultObject.orderId}}</p>
          <p v-html="resultObject.orderWay==0||resultObject.orderWay==1? '订购方式：购买': '订购方式：租金(月交易额达到条件才可返还)' "></p>
          <p>已签署协议：
            <span class="agreement " @click="jumpToserviceContract ">《{{CommonUtil.isMessagePackage(machineType)?"短信推广服务在线协议":"同福商家产品服务协议"}}》</span>
            <br/>
            <span class="service " @click="jumpToSecondData " v-if="resultObject.orderWay==2 ">《纵横客产品租赁激励方案(第二期)》</span>
          </p>
          <p v-if="contract">已签署合同：<span class="agreement" @click="showJkbContract">《聚客宝软件服务合同》</span></p>
          <p v-html=" '下单时间：'+CommonUtil.timestampToTime(resultObject.createTime) "></p>
          <p v-html=" '付款时间：'+CommonUtil.timestampToTime(resultObject.updateTime) "></p>
        </div>
      </div>
      <div class="btn-wrap ">
        <div class="btn pay " v-if="resultObject.status==1 " @click="payment(resultObject.orderId) ">立即支付</div>
        <router-link :to="{path:`/mallList/orderRecord/orderDetails/returnDeposit`,query:{orderId:resultObject.orderId,orderWay: resultObject.orderWay }} ">
          <div class="btn pay " v-if="resultObject.orderWay==1 ">变更订购方式</div>
        </router-link>
      </div>
    </div>
    <serviceContract ref="servContract"></serviceContract>
    <messageProtocol ref="messageProtocol"></messageProtocol>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import { MessageBox, Loadmore, Toast } from "mint-ui";
import jsBridge from "../../tools/jsBridge.js";
import serviceContract from "./serviceContract";
import messageProtocol from "./messageProtocol";
import config from "../../base/profile/config.json";
import contract from './contract';
import VueClipboard from "vue-clipboard2";
Vue.use(VueClipboard);

export default {
  name: "orderDetails",
  data() {
    return {
      CommonUtil: CommonUtil,
      resultObject: {},
      isEnd: false, //倒计时是否结束
      hr: "",
      min: "",
      sec: "",
      restTime: "",
      orderId: "",
      discountAmount: "", //优惠金额
      refuseClick: false,
      orderType:null,
      machineType:"",
      from:"",
      deviceInfo:[],
      jkbTypes: [34, 35], //聚客宝产品集合
      contract: null,
      contractParams: {},
      orderTypes: [5, 6, 7, 8, 9] // 不需要显示物流信息的订单类型
    };
  },
  methods: {
    showJkbContract() {
      this.contractParams = {
        machineToolId: this.contract.machineType,
        orderId: this.$route.query.orderId
      };
      this.$refs.contract.popupShow();
    },
    handleBack() {
      if(this.$refs.servContract.popupServiceVisible) {
        this.$refs.servContract.popupHide();
      } else if(this.$refs.messageProtocol.popupServiceVisible) {
        this.$refs.messageProtocol.popupHide();
      } else if (this.$refs.contract.popupVisible) {
        this.$refs.contract.popupHide();
      } else {
        if(String(this.$route.query.close) == 'true'){
          jsBridge.closeWindow();
        }else{
          this.$router.back();
        }
      }
    },
    // 跳转到服务协议
    jumpToserviceContract() {
      if(CommonUtil.isMessagePackage(this.machineType)){
         this.$refs.messageProtocol.popupShow();
      }else{
         this.$refs.servContract.popupShow();
      }
    },
    // 纵横客产品租赁激励方案(第二期)
    jumpToSecondData() {
      this.$router.push({ path: "/mallList/orderRecord/orderDetails/returnDeposit" });
    },
    doCopy(content) {
      if (!content) {
        return;
      }
      this.$copyText(content).then(
        e => {
          Toast("复制成功");
        },
        e => {
          Toast("您的系统版本过低,请长按手动复制");
        }
      );
    },
    devicePic(machineType) {
      let img = "./static/images/machines/defaultMachine.png";
      for (const e of this.deviceInfo) {
        if (e.machineType == machineType&&e.thumbnail){
          img = config.shopImgUrlPrefix + e.thumbnail;
          break;
        }
      }
      return img;
      //return require(`../../../static/images/machines/${window.CommonUtil.devicePic(machineType)}`);
    },
    // 获取订单详情数据
    loadData() {
      this.ajax({
        url: `app/orderService/orderDetail.do?orderId=${this.$route.query.orderId}`,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          if (res.success && res.resultObject) {
            this.resultObject = res.resultObject;
            this.discountAmount = (res.resultObject.totalAmount*10000 - res.resultObject.realAmount*10000)/10000;
            this.countdown();
            //聚客宝
            this.resultObject.machineLists.forEach(machine=> {
              machine.lists.forEach(item=> {
                if(this.jkbTypes.includes(item.machineType)) { 
                  this.contract = item;
                }
              })
            });
          } else {
            Toast(res.msg);
          }
        })
        .catch(err => {
 
        });
    },
    // 取消订单
    cancelOrder() {
      MessageBox({
        title: "确认提示",
        message: "取消订单后该记录将消失，确定要取消该订单吗？",
        showCancelButton: true,
        confirmButtonText: "确定"
      }).then(action => {
        if (action === "confirm") {
          this.ajax({
            url: `app/orderService/cancelOrder.do?orderId=${this.$route.query.orderId}`,
            type: "get",
            controlLoading: true
          })
            .then(res => {
              if (res.success) {
                this.$router.back();
              } else {
                Toast(res.msg);
              }
            })
            .catch(err => {
      
            });
        }
      });
    },
    encodePayInfo(string) {
      let str = string;
      let temp = str.split("&");
      let resultArray = [];
      for (let index = 0; index < temp.length; index++) {
        let item;
        if (temp[index].startsWith("sign=")) {
          item = [];
          item.push("sign");
          item.push(encodeURIComponent(temp[index].slice(5)));
        } else {
          item = temp[index].split("=");
          item[1] = encodeURIComponent(item[1]);
        }
        resultArray.push(item.join("="));
      }
      return resultArray.join("&");
    },
    // 支付接口
    payment(orderId,item) {
      
      if (this.refuseClick) {
        return;
      }
      this.refuseClick = true;

      let successMsg = "";//订购成功页的提示信息
      //联系人信息校验(推广套餐、码卡龙定制广告图、本地生活视频拍摄)
      if (CommonUtil.needLinkInfo(this.machineType)) {
        successMsg = "我们的业务人员会在2个工作日内与您联系，请保持手机畅通";
      }
      this.ajax({
        url: `app/orderService/toPayOrder.do?orderId=${orderId}`,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          if (res.success && res.resultObject) {
            this.orderId = res.resultObject.orderId;
            const router=this.from=="productDetails"?1:3;//解决 订购后关闭支付后，再从订单详情再支付，成功页点查看订单跳转错误的问题
            jsBridge.tradePay(
              {
                payType: "alipay",
                orderInfo: this.encodePayInfo(res.resultObject.orderInfo)
              },
              result => {
                if (result.resultObject.resultStatus == "9000") {
                  // this.forPayment();
                  this.refuseClick = false;
                  this.$router.push({ path: "/mallList/productDetails/payResult", query: { type: "true", toRouterNum: 3, toRouterRecordNum: router, msg: successMsg,machineType:this.machineType } });
                } else if (result.resultObject.resultStatus == "4000") {
                  // Toast(result.msg);
                  this.refuseClick = false;
                  this.$router.push({ path: "/mallList/productDetails/payResult", query: { type: "false", toRouterNum: 3, toRouterRecordNum: router } });
                } else {
                  this.refuseClick = false;
                  this.$router.push({ path: "/mallList/orderRecord/orderDetails", query: { orderId: this.orderId,orderType:this.orderType,machineType:this.machineType } });
                }
              }
            );
          } else {
            this.refuseClick = false;
            Toast(res.msg);
          }
        })
        .catch(err => {
          this.refuseClick = false;
        });
    },
    // 剩余时间倒计时
    countdown: function() {
      // debugger;
      let msec = "";
      let end = this.resultObject.effectTime;
      let now = parseInt(new Date().getTime());
      msec = end - now;

      // let day = parseInt(msec / 1000 / 60 / 60 / 24);
      let hr = parseInt((msec / 1000 / 60 / 60) % 24);
      let min = parseInt((msec / 1000 / 60) % 60);
      let sec = parseInt((msec / 1000) % 60);

      this.hr = hr > 9 ? hr : "0" + hr;
      this.min = min > 9 ? min : "0" + min;
      this.sec = sec > 9 ? sec : "0" + sec;
      this.restTime = this.hr + ":" + this.min + ":" + this.sec;
      if (this.hr == "00" && this.min == "00" && this.sec == "00") {
        this.$router.back(-1);
      }
      const that = this;
      setTimeout(function() {
        that.countdown();
      }, 1000);
    }
  },
  created() {
    this.orderType=this.$route.query.orderType;
    this.machineType=this.$route.query.machineType;
     CommonUtil.getDeviceInfo().then(data => {
        this.deviceInfo = data;
        this.loadData();
    });
    
  },
  components: {
    customHeader,
    serviceContract,
    messageProtocol,
    contract
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.from = from.name;
    });
  }, 
};
</script>
<style lang='scss' scoped>
@import "mall";
</style>
